<?php

use Illuminate\Http\Request;

if (!function_exists('toUnderLine')){
    /**
     * 字符串转骆驼峰
     * @param $str
     * @return array|string|string[]|null
     */
    function toUnderLine($str){
        return preg_replace_callback('/([-_\/]+([a-z]))/i',function($matches){
            return strtoupper($matches[2]);
        },$str);
    }
}

if (!function_exists('vue_render')){
    /**
     * vue_render vue组件渲染函数封装
     * @param $component
     * @param array $props
     * @param Request|null $request
     * @return string
     */
    function vue_render($component, array $props = [], Request $request = null): string
    {
        $domId = "app_".md5($component.time().uniqid());
        $props['request'] = $request??request();
        $name = toUnderLine($component);
        $defaultProps = [
            "data-id"=>$domId,
            "name"=>$name,
            "component"=>$component,
            "props"=>$props
        ];
        $data = json_encode($defaultProps,JSON_UNESCAPED_UNICODE);
        return <<<HTML
<div id="{$domId}"></div>
<script type="module">app_init(`#{$domId}`,`{$data}`);</script>
HTML;
    }
}
